/*图片滚动*/
function Slider (option){
    this.thumbWrap = option.thumbWrap;
    this.thumbList = option.thumbList || this.thumbWrap.find('li');
    this.heroList = option.heroList;
    this.leftArrow = option.leftArrow;
    this.rightArrow = option.rightArrow;
    this.defaultCount = option.defaultCount || 5;
    this.callback = option.callback;
    this.listLength = this.heroList.length; // 总个数

    this.initEvents();

}
Slider.prototype = {
    initEvents: function () {
        var _self = this;
        _self.refreshArrow();
        _self.controlEvents();
    },
    refreshArrow: function () {
        var _self = this;
        var _singleThumbWidth = _self.thumbWrap.children('li').eq(0).outerWidth(true);
        var _wrapOffset = _self.thumbWrap.position().left;
        var _isLastPage = _self.thumbWrap.parent('div').outerWidth(true) - _wrapOffset >= _self.listLength * _singleThumbWidth;

        if ( _self.listLength <= _self.defaultCount ) {
            _self.rightArrow.addClass('disable');
            _self.leftArrow.addClass('disable');
        }else{
            if ( _wrapOffset === 0 ) {
                _self.leftArrow.addClass('disable');
                _self.rightArrow.removeClass('disable');
            }else if( _isLastPage ) {
                _self.leftArrow.removeClass('disable');
                _self.rightArrow.addClass('disable');
            }else{
                _self.leftArrow.removeClass('disable');
                _self.rightArrow.removeClass('disable');
            }
        }
    },
    controlEvents: function () {
        var _self = this;
        _self.thumbList.on('click',function(e){
            if ( $(this).hasClass("cur") ) return;
            e.preventDefault();
            var _currentImg = _self.heroList.parent('ul').find(".cur");
            var _index = $(this).index();
            $(this).addClass("cur").siblings("li").removeClass("cur");
            $(_currentImg).removeClass("cur").fadeOut("500").css("zIndex", 0);
            _self.heroList.eq(_index).addClass("cur").css("zIndex", 51).fadeIn("500", function() {
                $(this).css("zIndex", 50);
            });
        });
        _self.leftArrow.on('click', function(e) {
            if ( $(this).hasClass('disable') ) return;
            e.preventDefault();
            _self.transformPage('left');
        });
        _self.rightArrow.on('click', function(e) {
            if ( $(this).hasClass('disable') ) return;
            e.preventDefault();
            _self.transformPage('right');
        });
    },
    transformPage: function (direction) {
        var _self = this;
        if ( direction === 'left' ) {
            _self.thumbList.parent('ul').animate({
                left: "+="+(_self.defaultCount*147)
            }, 300, function function_name (argument) {
                _self.refreshArrow();
            });
        }else if ( direction === 'right' ) {
            _self.thumbList.parent('ul').animate({
                left: "-="+(_self.defaultCount*147)
            }, 300, function function_name (argument) {
                _self.refreshArrow();
            });
        }
    }
};

var Page = {
    btp : baidu.template,
    calendarObj : {},
    rightOrderInfo : {},
    order : {},
    initSlider : function(){
        var productSlider = new Slider({
            thumbWrap  : $('#hero-thumb ul'),
            heroList   : $('#hero-header li'),
            leftArrow  : $('#hero-thumb-left'),
            rightArrow : $('#hero-thumb-right'),
            callback   : function(){}
        });
    },
    initCalendar : function(){
        var _self = this,
            userClickDate = '',
            calendar = $("#calendar"),
            firstDate = calendar.attr('firstdate'),
            configs = {
                month: firstDate.split('-')[1]-1,
                header: {
                    left: 'prev',
                    center: 'title',
                    right: 'next'
                },
                titleFormat: {
                    month: 'yyyy年M月'
                },
                editable: false,
                selectable: true,
                selectHelper: false,
                monthNames: ["1月", "2月", "3月", "4月","5月","6月","7月","8月","9月","10月","11月","12月"],
                monthNamesShort: ["1月", "2月", "3月", "4月","5月","6月","7月","8月","9月","10月","11月","12月"],
                dayNamesShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
                viewRender : function(view, element){
                    //view渲染完成之后
                    var start_date = $.fullCalendar.formatDate(view.start, 'yyyy-MM-dd');

                    if(start_date < firstDate){
                        calendar.find('.fc-button-prev').hide();
                    }else{
                        calendar.find('.fc-button-prev').show();
                    }
                },
                dayClick: function(date, isAllday, jsEvent, view) {
                    //this : 当前点击的td
                    //view : 整个calendar的weekview

                    //没有价格的日子禁止点击
                    if($(this).hasClass('data-not-inited')){
                        return;
                    }
                    calendar.find('.data-clicked').removeClass('data-clicked').addClass('data-inited');
                    $(this).removeClass('data-inited').addClass('data-clicked');

                    //数据层变颜色 
                    calendar.find('.fc-event-data-clicked').removeClass('fc-event-data-clicked');
                    var currentDate = $.fullCalendar.formatDate(date, 'yyyy-MM-dd'),
                        dataDiv = calendar.find('.fc-event').filter('[data-date='+currentDate+']');
                    dataDiv.addClass('fc-event-data-clicked');

                    var price = dataDiv.filter('.fc-event-data-price').attr('data-price');
                    //右侧预定价格联动
                    _self.rightOrderInfo.selectOneDay(currentDate);
                    //右侧订单单价变化
                    _self.rightOrderInfo.setSelectDatePrice(price);
                    ///右侧订单总价变化
                    _self.rightOrderInfo.refreshTotalPrice();
                    //下单
                    _self.order.makeorder();
                },
                eventSources: [
                    {
                        url: "/tp/"+bt.context('pk')+"/calendar/events/?only-price=1"
                    },
                    {
                        url: "/tp/"+bt.context('pk')+"/calendar/events/?only-stock=1"
                    }
                ],
                eventAfterRender: function(event, element,view) {
                    //element : 当前渲染的数据层div
                    //view : 整个calendar的weekview
                    var currentDate = $.fullCalendar.formatDate(event.start, 'yyyy-MM-dd');
                    //日期cell偏移量(如 {row:2,col:6})，根据这个偏移量找到对应日子的td，然后上背景色
                    var cellOffset = view.dateToCell(new Date(event.start)),
                        currentRow = view.allDayRow(cellOffset.row);
                    var currentCell = $(currentRow).find('td').eq(cellOffset.col);
                    //是否是用户点击右侧选择时间，跳转过来的
                    if(userClickDate == currentDate){
                        currentCell.addClass('data-clicked');
                    }else{
                        currentCell.addClass('data-inited');
                    }

                    //针对价格和库存设置不同样式
                    var eventTitle = $(element).find('.fc-event-title').html();
                    if(event.source.url.indexOf('only-price') !=-1 ){
                        $(element).attr('data-price',eventTitle);
                        $(element).addClass('fc-event-data-price');
                        $(element).find('.fc-event-title').html(eventTitle);
                        $(element).css('top',currentCell.position().top+30);
                        currentCell.find('.fc-day-content').addClass('two-content');
                    }else if(event.source.url.indexOf('only-stock') !=-1 ){
                        $(element).attr('data-stock',eventTitle);
                        $(element).addClass('fc-event-data-stock');
                        $(element).find('.fc-event-title').addClass('stock').html('剩余：'+eventTitle);
                        $(element).css('top',currentCell.position().top+45);
                        currentCell.find('.fc-day-content').addClass('two-content');
                    }
                    //用户点击右侧日期选择跳转到其他月份，渲染后过后增加选中背景，并进行价格计算
                    if(userClickDate == currentDate){
                        $(element).addClass('fc-event-data-clicked');
                        if(event.source.url.indexOf('only-price') !=-1 ){
                            //右侧订单单价变化
                            _self.rightOrderInfo.setSelectDatePrice(eventTitle);
                            ///右侧订单总价变化
                            _self.rightOrderInfo.refreshTotalPrice();
                        }
                    }
                    $(element).attr('data-date',currentDate);
                },
                eventAfterAllRender:function(view){
                    //将没有价格的日子设置特殊样式
                    calendar.find('.fc-widget-content').each(function(index,item){
                        if(!$(this).hasClass('data-inited') && !$(this).hasClass('data-clicked') ){
                            $(this).addClass('data-not-inited');
                        }
                    });
                    //用户点击右侧预定价格，选择的时间重置
                    userClickDate='';
                }
            };
        var calendarInstance = calendar.fullCalendar(configs);
        this.calendarObj = {
            instance : calendarInstance,
            selectOneDay : function(year,month,dateofmonth){
                var date = year+'-'+month+'-'+dateofmonth,
                    startDate = $.fullCalendar.formatDate(calendarInstance.fullCalendar('getView').start, 'yyyy-MM-dd'),
                    endDate = $.fullCalendar.formatDate(calendarInstance.fullCalendar('getView').end, 'yyyy-MM-dd');
                //当前月份内跳转，仅改变选中样式，否则进行calendar日期跳转渲染
                if(startDate <= date  && date < endDate){
                    //颜色改变
                    calendar.find('.data-clicked').removeClass('data-clicked').addClass('data-inited');
                    calendar.find('.fc-event-data-clicked').removeClass('fc-event-data-clicked');

                    
                    var dateTd = calendar.find('.fc-widget-content').filter('[data-date='+date+']'),
                        dateData = calendar.find('.fc-event').filter('[data-date='+date+']');
                    dateTd.removeClass('data-inited').addClass('data-clicked');
                    dateData.addClass('fc-event-data-clicked');

                    var price = dateData.filter('.fc-event-data-price').attr('data-price');
                    //右侧订单单价变化
                    _self.rightOrderInfo.setSelectDatePrice(price);
                    ///右侧订单总价变化
                    _self.rightOrderInfo.refreshTotalPrice();
                }else{
                    //跳到其他月份，需要在eventAfterRender里面进行选中渲染
                    //此处month-1，是因为fullcalendar的bug，上面初始化中的configs.month也是如此
                    calendarInstance.fullCalendar('gotoDate',year,month-1,dateofmonth);
                    userClickDate = date;
                }
                
            }
        }
        
    },
    initProductInfo : function(){
        $('#btn-explain').hover(function() {
            $('#explain-popup').removeClass('hidden');
        }, function() {
            $('#explain-popup').addClass('hidden');
        });
    },
    initNav: function(){
        var nav = $('#nav'),
            navList = nav.find('li'),
            navContent = $('#other-content'),
            contentBox = navContent.find('.box'),
            contentBoxTopMap = {},
            isclicked = false;
        
        
        //点击滚动
        navList.on('click',function(e){
            isclicked = true;
            var index = $.inArray(this,navList.toArray()),
                top = contentBox.eq(index).offset().top-52;
            navList.filter('.cur').removeClass('cur');
            $(this).addClass('cur');
            $('body').animate({
                scrollTop: top-20
            }, 200, function() {
                isclicked = false;
            });
        })
        $(window).on('scroll',function(){
            var scrollTop = $(window).scrollTop(),
                navContentTop = navContent.offset().top;
            //吸顶
            if(scrollTop > navContentTop -5){
                navContent.addClass('nav-content-fixed');
                nav.addClass('nav-fixed');
            }else{
                nav.removeClass('nav-fixed');
                navContent.removeClass('nav-content-fixed');
            }
            if( isclicked ){
                return;
            }
            contentBox.each(function(index,item){
                contentBoxTopMap[index] = $(item).offset().top-52;
            });
            //tab选中状态
            for(var i=0;i<navList.length;i++){
                if(i == 0){
                    //页面位于第一个上方
                    if(scrollTop < contentBoxTopMap[0] && !navList.eq(0).hasClass('cur')){
                        navList.filter('.cur').removeClass('cur');
                        navList.eq(0).addClass('cur');
                        return;
                    }
                }else{
                    //页面位于两个模块之间
                    var beforeBoxHeight = contentBox.eq(i-1).height();
                    if(scrollTop > contentBoxTopMap[i-1] + beforeBoxHeight  && scrollTop < contentBoxTopMap[i] && !navList.eq(i).hasClass('cur')){
                        navList.filter('.cur').removeClass('cur');
                        navList.eq(i).addClass('cur');
                        return;
                    }
                }
            }
        });
    },
    initSchedulesNav: function(){
        var nav = $('#schedules-nav'),
            navList = nav.find('li'),
            navContent = $('.schedules-inner'),
            contentBox = navContent.find('.schedules-main li'),
            contentBoxTopMap = {},
            isclicked = false;
        
        
        //点击滚动
        navList.on('click',function(e){
            isclicked = true;
            var index = $.inArray(this,navList.toArray()),
                top = contentBox.eq(index).offset().top-52;
            navList.filter('.cur').removeClass('cur');
            $(this).addClass('cur');
            $('body').animate({
                scrollTop: top-20
            }, 200, function() {
                isclicked = false;
            });
        });
        $(window).on('scroll',function(){
            var scrollTop = $(window).scrollTop(),
                navContentTop = navContent.offset().top,
                navContentHeight = navContent.outerHeight(),
                navHeight = nav.outerHeight();
            //吸顶
            if( (scrollTop > navContentTop - 72) && (scrollTop < navContentTop + navContentHeight - navHeight - 72) ){
                nav.addClass('schedules-nav-fixed');
            }else{
                nav.removeClass('schedules-nav-fixed');
            }
            if( isclicked ){
                return;
            }
            contentBox.each(function(index,item){
                contentBoxTopMap[index] = $(item).offset().top-52;
            });
            //tab选中状态
            for(var i=0;i<navList.length;i++){
                if(i == 0){
                    //页面位于第一个上方
                    if(scrollTop < contentBoxTopMap[0] && !navList.eq(0).hasClass('cur')){
                        navList.filter('.cur').removeClass('cur');
                        navList.eq(0).addClass('cur');
                        return;
                    }
                }else{
                    //页面位于两个模块之间
                    var beforeBoxHeight = contentBox.eq(i-1).height();
                    if(scrollTop > contentBoxTopMap[i-1] + beforeBoxHeight  && scrollTop < contentBoxTopMap[i] && !navList.eq(i).hasClass('cur')){
                        navList.filter('.cur').removeClass('cur');
                        navList.eq(i).addClass('cur');
                        return;
                    }
                }
            }
        });
    },
    initHotelImgEvents : function () {
        var _singleWidth = 380;
        $("#hotels-img-left").on("click", function(e) {
            var _ul = $(this).parent(".hotels-img").find("ul");
            _ul.animate({left: "+="+_singleWidth}, 500, function () {
                _refreshHotelArrow(_ul);
            });
            e.preventDefault();
        });
        $("#hotels-img-right").on("click", function(e) {
            var _ul = $(this).parent(".hotels-img").find("ul");
            _ul.animate({left: "-="+_singleWidth}, 500, function () {
                _refreshHotelArrow(_ul);
            });
            e.preventDefault();
        });
        var _refreshHotelArrow = function (ul) {
            var _leftBtn = $("#hotels-img-left"),
                _rightBtn = $("#hotels-img-right"),
                _totleWidth = ul.find('li').length * _singleWidth;
            if ( ul.position().left >= 0 ) {
                _leftBtn.addClass('hide');
                _rightBtn.removeClass('hide');
            }else if ( ul.position().left <= (_singleWidth -_totleWidth) ) {
                _rightBtn.addClass('hide');
                _leftBtn.removeClass('hide');
            }else{
                _rightBtn.removeClass('hide');
                _leftBtn.removeClass('hide');
            }
        };
    },
    initRelatedTrips : function () {
        var _tripContent = '';
        var _url = '/tp/'+ bt.context('pk') +'/related-trips/';
        $.ajax({
            url: _url,
            type: 'GET',
            dataType: 'json',
            success: function (data) {
                _tripContent = Page.btp('related-trips-templates', {list: data});
                $(_tripContent).appendTo('#related-trips ul');
            }
        });
        
    },
    initSubProduct : function () {
        function unfoldList (e) {
            e.preventDefault();
            $(this).hide();
            $('#subproduct').find('ul').removeClass('subproduct-hide');
        }
        $('#subproduct-more').on('click', unfoldList);
    },
    initHotels : function () {
        function unfoldList (e) {
            e.preventDefault();
            $(this).hide();
            $('#hotels-list').removeClass('hotels-hide');
        }
        $('#hotels-more').on('click', unfoldList);
    },
    initRightOrderInfo : function(){

        var _self = this;
        var productInfoDate = $('#order-date-selector'),
            productInfoDateText = productInfoDate.find('.date-selector-text'),
            productInfoDateList = productInfoDate.find('.date-selector-list');

        var productOrderCount = $('#product-order-count'),
            productOrderPrice = $('#product-order-price');

        this.rightOrderInfo = {
            selectOneDay : function(dateStr){
                productInfoDateText.html(dateStr);
            },
            getSelectDate : function(){
                return productInfoDateText.html();
            },
            getSelectPeopleCount : function(){
                return productOrderCount.val();
            },
            getSelectDatePrice : function(){
                return productOrderPrice.attr('data-price');
            },
            setSelectDatePrice : function(price){
                productOrderPrice.attr('data-price',price);
            },
            refreshTotalPrice : function(){
                //价格变化
                productOrderPrice.html(productOrderPrice.attr('data-price')*productOrderCount.val());
            }
        }
        //日期选择操作
        productInfoDate.on('mouseenter',function(){
            productInfoDateList.show();
        }).on('mouseleave',function(){
            productInfoDateList.hide();
        });
        productInfoDateList.find('li').click(function(){
            productInfoDateList.hide();
            productInfoDateText.html($(this).attr('data-date'));
            //价格日历联动
            if(_self.calendarObj.instance){
                var dateArr = $(this).attr('data-date').split('-');
                _self.calendarObj.selectOneDay(dateArr[0],dateArr[1],dateArr[2]);
            }
        });

        //人数选择操作
        productOrderCount.on('change',function(){
            _self.rightOrderInfo.refreshTotalPrice();
        });

        //预订按钮点击
        $('#product-book-now').click(function(){
            _self.order.makeorder();
        });
        
        
    },
    initOrder : function(){
        var _self = this,
            orderDialog = $('#order-popup'),
            popupPoints = $('#popup-points'),
            popupPointsInput = $('#popup-points-input'),
            popupPointsResult = $('#popup-points-result'),
            popupCoupon = $('#popup-coupon'),
            popupCouponInput = $('#popup-coupon-input'),
            popupCouponResult = $('#popup-coupon-result'),
            popupTotalPrice = $('#popup-total-price'),
            popupCount = $('#popup-order-count'),
            
            total_price = 0,   //总价
            single_price = 0,  //单价
            ratio = bt.context('ratio'),    //积分与人民币比率
            user_points = bt.context('user_points'),    //用户积分
            max_points = bt.context('max_points'), //单个产品最多可用积分
            coupon_discount = 0.0; //面包券折扣

        this.order = {
            makeorder : function(){
                var subproduct = $('#subproduct');
                if(subproduct.length > 0){
                    var top = subproduct.offset().top;
                    $('body').animate({
                        scrollTop: top-20
                    }, 200, function() {
                    });
                }else{
                    this.openDialog();
                }
            },
            openDialog : function(btn){
                if(!bt.context('UserIsAuthenticated')){
                    bt.misc.redirect_to_login();
                    return;
                }
                var title = bt.context('title'),
                    date = _self.rightOrderInfo.getSelectDate(),
                    count = _self.rightOrderInfo.getSelectPeopleCount(),
                    price = _self.rightOrderInfo.getSelectDatePrice();
                if($('.subproduct-book-now').length > 0){
                    title = bt.context('title')+'/'+$(btn).attr('data-title');
                    price = $(btn).attr('data-price');
                }

                $('#popup-product-title').html(title);
                $('#popup-order-date').find('.date-selector-text').html(date);
                popupCount.val(count);
                single_price = price;

                this.calculatePrice();
                bt.misc.showPopup(orderDialog,false);
            },
            initDialog : function(){
                var _self = this;
                //关闭按钮
                orderDialog.find('.close').on('mouseover',function(){
                    $(this).addClass('product-icons-popup_close_h');
                }).on('mouseout',function(){
                    $(this).removeClass('product-icons-popup_close_h');
                });
                //日期选择
                var productInfoDate = $('#popup-order-date'),
                    productInfoDateText = productInfoDate.find('.date-selector-text'),
                    productInfoDateList = productInfoDate.find('.date-selector-list');
                productInfoDate.on('mouseenter',function(){
                    productInfoDateList.show();
                }).on('mouseleave',function(){
                    productInfoDateList.hide();
                });
                productInfoDateList.find('li').click(function(){
                    productInfoDateList.hide();
                    productInfoDateText.html($(this).attr('data-date'));
                });
                //人数变化
                popupCount.on('change',function(){
                    _self.calculatePrice();
                })
                //优惠
                popupPoints.find('a').click(function(){
                    popupPoints.find('.hidden').toggle();
                });
                popupCoupon.find('a').click(function(){
                    popupCoupon.find('.hidden').toggle();
                });
                //积分
                popupPointsInput.on('change', function() {
                    var val = $(this).val();
                    if(isNaN(val)){
                        popupPoints.find('.error-text').show().text('您输入的积分无效，请重新输入');
                        popupPointsInput.val('');
                    }else{
                        val = parseInt(val, 10);
                        var avaliable_user_points = Math.min(Math.ceil(popupCount.val() *single_price / ratio), user_points);
                        if (val > avaliable_user_points) {
                            popupPoints.find('.error-text').show().text('您输入的积分无效，请重新输入');
                            popupPointsInput.val('');
                        }else if(max_points < 9999999 && val > popupCount.val()*max_points){
                            popupPoints.find('.error-text').show().text('此产品单个最多使用'+max_points+'积分');
                            popupPointsInput.val('');
                        }
                    }
                    _self.calculatePrice();
                }).on('focus',function(){
                    popupPoints.find('.error-text').hide().text("");
                });
                //面包券
                popupCouponInput.on('change',function(){
                    _self.calculatePrice();
                }).on('focus',function(){
                    popupCoupon.find('.error-text').hide().text("");
                });
            },
            calculatePrice : function(){
                var count = popupCount.val();

                total_price = count * single_price;
                var total_max_points = count * max_points;

                var avaliable_user_points = Math.min(Math.ceil(total_price / ratio), user_points, total_max_points);
                var actual_use_points = Math.min(avaliable_user_points, parseInt(popupPointsInput.val(), 10)) || 0;

                //使用积分减去的价格
                var pointsVal = Math.min(total_price, (actual_use_points * ratio)).toFixed(2);
                popupPointsResult.text('- ' + pointsVal);

                if(popupCouponInput.val()){
                    $.ajax({
                        url: "/tp/order/coupon_code/",
                        type: "GET",
                        data: {
                            cc: popupCouponInput.val(),
                            tp: total_price
                        },
                        async: false,
                        success: function(resp) {
                            if ( resp.errmsg ) {
                                popupCouponInput.val("");
                                coupon_discount = 0.0;
                                popupCoupon.find('.error-text').show().text(resp.errmsg);
                            }else{
                                coupon_discount = resp.discount;
                            }

                            //使用优惠券减去的价格
                            popupCouponResult.text('- ' + coupon_discount.toFixed(2));
                            popupTotalPrice.text(Math.max(0, (total_price - actual_use_points * ratio - coupon_discount)).toFixed(2));
                        }
                    });
                }else{
                    popupTotalPrice.text(Math.max(0, (total_price - actual_use_points * ratio - coupon_discount)).toFixed(2));
                }
                
            }
        }
        this.order.initDialog();
        $('.subproduct-book-now').click(function(){
            _self.order.openDialog(this);
        });

    }
};
$(function(){
    
    Page.initProductInfo();
    Page.initSlider();
    Page.initCalendar();
    Page.initRightOrderInfo();
    Page.initSubProduct();
    Page.initHotels();
    Page.initHotelImgEvents();
    Page.initRelatedTrips();
    Page.initNav();
    Page.initSchedulesNav();
    Page.initOrder();
});